import { useRequest } from 'ahooks'
import {
  forwardRef,
  useContext,
  useEffect,
  useImperativeHandle,
  useRef,
  useState
} from 'react'
import CountUp from 'react-countup'

import { BarModule } from '../../Bar'
import { BigPre2 } from '../../BigPre/index2'
import { MinPre } from '../../MinPre'
import { ModuleTitle } from '../../ModuleTitle'
import { ContentTsx } from '../../contentTsx'
import { colorLinearData, getCarData, getCrbtData, getcrfx } from '../../data'
import type { SwitchAndIntervalRef } from '../../interface'
import { generateCountArray } from '../../utils'

const CarDataModule = forwardRef<SwitchAndIntervalRef, any>(
  (prop: any, ref) => {
    const { selectedAssociationItem, refreshFlag } = useContext(ContentTsx)
    const [optionData, setOptionData] = useState<any>()
    const MinPreRef = useRef<{ resize: () => void }>(null)
    const BigPreRef = useRef<{ resize: () => void }>(null)
    const BarRef = useRef<{ resize: () => void }>(null)
    //车辆入网总数
    const [allSum, setAllSum] = useState<number>(0)
    const allSumRef = useRef<number>(0)
    const [prevAllSum, setPrevAllSum] = useState<number>(0)
    const [endAllSum, setEndAllSum] = useState<number>(0)
    const prevAllSumRef = useRef<number>(0)
    const endAllSumRef = useRef<number>(0)

    //今日作业车辆
    const [zySum, setZySum] = useState<number>(0)
    const zySumRef = useRef<number>(0)
    const [prevZySum, setPrevZySum] = useState<number>(0)
    const [endZySum, setEndZySum] = useState<number>(0)
    const prevZySumRef = useRef<number>(0)
    const endZySumRef = useRef<number>(0)

    // 当前在途车辆
    const [ztSum, setZtSum] = useState<number>(0)
    const ztSumRef = useRef<number>(0)
    const [prevZtSum, setPrevZtSum] = useState<number>(0)
    const [endZtSum, setEndZtSum] = useState<number>(0)
    const prevZtSumRef = useRef<number>(0)
    const endZtSumRef = useRef<number>(0)

    // timeout
    const allSumTimeoutIdRef = useRef<any>()
    const zySumTimeoutIdRef = useRef<any>()
    const ztSumTimeoutIdRef = useRef<any>()

    //数据/时间 分组
    const allSumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })
    const zySumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })
    const ztSumUpGroupRef = useRef<{
      countGroup: number[]
      timeGroup: number[]
    }>({
      countGroup: [],
      timeGroup: []
    })

    const allSumUpGroupIndexRef = useRef<number>(0)
    const zySumUpGroupIndexRef = useRef<number>(0)
    const ztSumUpGroupIndexRef = useRef<number>(0)

    function clearCountUp() {
      if (allSumTimeoutIdRef.current) {
        clearTimeout(allSumTimeoutIdRef.current)
      }
      if (zySumTimeoutIdRef.current) {
        clearTimeout(zySumTimeoutIdRef.current)
      }

      if (ztSumTimeoutIdRef.current) {
        clearTimeout(ztSumTimeoutIdRef.current)
      }
    }

    //入网车辆总数
    function _recursionAllSumSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > allSumUpGroupRef.current.countGroup.length - 1) {
        if (allSumTimeoutIdRef.current) {
          clearTimeout(allSumTimeoutIdRef.current)
        }
        if (endAllSumRef.current !== allSumRef.current) {
          console.error(
            `endAllSumRef.current 【${endAllSumRef.current}】!==allSumRef.current 【${allSumRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        allSumUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s
      if (allSumTimeoutIdRef.current) {
        clearTimeout(allSumTimeoutIdRef.current)
      }
      allSumTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevAllSumRef.current = endAllSumRef.current
        } else if (gorupIndex > 0) {
          prevAllSumRef.current +=
            allSumUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevAllSum(prevAllSumRef.current)

        const currEndCount =
          allSumUpGroupRef.current.countGroup[gorupIndex] +
          prevAllSumRef.current
        endAllSumRef.current = currEndCount
        // console.log(
        //   "--prevAllSumRef.current--endAllSumRef.current--:",
        //   prevAllSumRef.current,
        //   currEndCount
        // )
        setEndAllSum(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleAllSumCountUpEnd = () => {
      allSumUpGroupIndexRef.current += 1
      _recursionAllSumSetStartEndCount(allSumUpGroupIndexRef.current)
    }

    //今日作业车辆
    function _recursionZySumSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > zySumUpGroupRef.current.countGroup.length - 1) {
        if (zySumTimeoutIdRef.current) {
          clearTimeout(zySumTimeoutIdRef.current)
        }
        if (endZySumRef.current !== zySumRef.current) {
          console.error(
            `endZySumRef.current 【${endZySumRef.current}】!==zySumRef.current 【${zySumRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        zySumUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s
      if (zySumTimeoutIdRef.current) {
        clearTimeout(zySumTimeoutIdRef.current)
      }
      zySumTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevZySumRef.current = endZySumRef.current
        } else if (gorupIndex > 0) {
          prevZySumRef.current +=
            zySumUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevZySum(prevZySumRef.current)

        const currEndCount =
          zySumUpGroupRef.current.countGroup[gorupIndex] + prevZySumRef.current
        endZySumRef.current = currEndCount
        // console.log(
        //   "--prevZySumRef.current--endZySumRef.current--:",
        //   prevZySumRef.current,
        //   currEndCount
        // )
        setEndZySum(currEndCount)
      }, timeoutTime * 1000)
    }

    const handleZySumCountUpEnd = () => {
      zySumUpGroupIndexRef.current += 1
      _recursionZySumSetStartEndCount(zySumUpGroupIndexRef.current)
    }

    //当前在途车辆
    function _recursionZtSumSetStartEndCount(gorupIndex: number) {
      if (gorupIndex > ztSumUpGroupRef.current.countGroup.length - 1) {
        if (ztSumTimeoutIdRef.current) {
          clearTimeout(ztSumTimeoutIdRef.current)
        }
        if (endZtSumRef.current !== ztSumRef.current) {
          console.error(
            `endZtSumRef.current 【${endZtSumRef.current}】!==ztSumRef.current 【${ztSumRef.current}】`
          )
        }
        return
      }
      const timeoutTime = Math.max(
        1,
        ztSumUpGroupRef.current.timeGroup[gorupIndex] - 1
      ) //CountUp duration需要1s
      if (ztSumTimeoutIdRef.current) {
        clearTimeout(ztSumTimeoutIdRef.current)
      }
      ztSumTimeoutIdRef.current = setTimeout(() => {
        if (gorupIndex === 0) {
          //初始化时是从1开始的，以后每次更新是从0开始的
          prevZtSumRef.current = endZtSumRef.current
        } else if (gorupIndex > 0) {
          prevZtSumRef.current +=
            ztSumUpGroupRef.current.countGroup[gorupIndex - 1]
        }
        setPrevZtSum(prevZtSumRef.current)

        const currEndCount =
          ztSumUpGroupRef.current.countGroup[gorupIndex] + prevZtSumRef.current
        endZtSumRef.current = currEndCount
        // console.log(
        //   "--prevZtSumRef.current--endZtSumRef.current--:",
        //   prevZtSumRef.current,
        //   currEndCount
        // )
        setEndZtSum(currEndCount)
      }, timeoutTime * 1000)
    }
    const handleZtSumCountUpEnd = () => {
      //初始化CountUp.start === 0 && CountUp.end === 0 时也会在duration 1s之后执行onEnd回调函数
      ztSumUpGroupIndexRef.current += 1
      _recursionZtSumSetStartEndCount(ztSumUpGroupIndexRef.current)
    }

    //5分钟刷新
    function _intervalRefresh() {
      clearCountUp()
      getcrfx({ entId: selectedAssociationItem.key })
        .then((data) => {
          setOptionData(data)
          const { allSum = 0, zySum = 0, ztSum = 0 } = data
          setAllSum(allSum)
          allSumRef.current = allSum
          setZySum(zySum)
          zySumRef.current = zySum
          setZtSum(ztSum)
          ztSumRef.current = ztSum
          //车辆入网总数
          const allSumDiff = allSum - endAllSumRef.current
          if (allSumDiff === 0) {
            return
          } else {
            allSumUpGroupIndexRef.current = 0
            allSumUpGroupRef.current = generateCountArray(
              endAllSumRef.current,
              allSum
            )
            if (allSumDiff < 0) {
              allSumUpGroupRef.current = {
                countGroup: allSumUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: allSumUpGroupRef.current.timeGroup
              }
            }
            _recursionAllSumSetStartEndCount(allSumUpGroupIndexRef.current)
          }

          //今日作业车辆
          const zySumDiff = zySum - endZySumRef.current
          if (zySumDiff === 0) {
            return
          } else {
            zySumUpGroupIndexRef.current = 0
            zySumUpGroupRef.current = generateCountArray(
              endZySumRef.current,
              zySum
            )
            if (zySumDiff < 0) {
              zySumUpGroupRef.current = {
                countGroup: zySumUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: zySumUpGroupRef.current.timeGroup
              }
            }
            _recursionZySumSetStartEndCount(zySumUpGroupIndexRef.current)
          }

          //当前在途车辆
          const ztSumDiff = ztSum - endZtSumRef.current
          if (ztSumDiff === 0) {
            return
          } else {
            ztSumUpGroupIndexRef.current = 0
            ztSumUpGroupRef.current = generateCountArray(
              endZtSumRef.current,
              ztSum
            )
            if (ztSumDiff < 0) {
              ztSumUpGroupRef.current = {
                countGroup: ztSumUpGroupRef.current.countGroup.map(
                  (count) => count * -1
                ),
                timeGroup: ztSumUpGroupRef.current.timeGroup
              }
            }
            _recursionZtSumSetStartEndCount(ztSumUpGroupIndexRef.current)
          }
        })
        .catch((err: any) => {
          console.error('--CarDataModule--_intervalRefresh--err--:', err)
        })
    }

    //初始化/切换协会时 获取数据
    function _initialOrSwitchAssociation(
      type: 'inital' | 'switchAssociation',
      associationKey: string
    ) {
      if (type === 'switchAssociation') {
        clearCountUp()
        //车辆入网总数
        setAllSum(0)
        allSumRef.current = 0
        setPrevAllSum(0)
        setEndAllSum(0)
        prevAllSumRef.current = 0
        endAllSumRef.current = 0

        //今日作业车辆
        setZySum(0)
        zySumRef.current = 0
        setPrevZySum(0)
        setEndZySum(0)
        prevZySumRef.current = 0
        endZySumRef.current = 0

        // 当前在途车辆
        setZtSum(0)
        ztSumRef.current = 0
        setPrevZtSum(0)
        setEndZtSum(0)
        prevZtSumRef.current = 0
        endZtSumRef.current = 0

        //数据/时间 分组
        allSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        zySumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }
        ztSumUpGroupRef.current = {
          countGroup: [],
          timeGroup: []
        }

        allSumUpGroupIndexRef.current = 0
        zySumUpGroupIndexRef.current = 0
        ztSumUpGroupIndexRef.current = 0
      }
      getcrfx({ entId: associationKey })
        .then((data) => {
          setOptionData(data)
          const { allSum = 0, zySum = 0, ztSum = 0 } = data
          setAllSum(allSum)
          allSumRef.current = allSum
          setZySum(zySum)
          zySumRef.current = zySum
          setZtSum(ztSum)
          ztSumRef.current = ztSum

          if (allSum > 0) {
            endAllSumRef.current = allSum
            setEndAllSum(allSum)
          }

          if (zySum > 0) {
            endZySumRef.current = zySum
            setEndZySum(zySum)
          }

          if (ztSum > 0) {
            endZtSumRef.current = ztSum
            setEndZtSum(ztSum)
          }
        })
        .catch((err: any) => {
          console.error(
            '--CarDataModule--_initialOrSwitchAssociation--err--:',
            err
          )
        })
    }

    useImperativeHandle(ref, () => ({
      switchAssociation: (newAssociationId) => {
        // console.log("--CarDataModule---switchAssociation--newAssociationId--:", newAssociationId)
        _initialOrSwitchAssociation('switchAssociation', newAssociationId)
      },
      intervalRefresh: _intervalRefresh,
      resize: () => {
        if (MinPreRef.current) {
          MinPreRef.current.resize()
        }
        if (BigPreRef.current) {
          BigPreRef.current.resize()
        }
        if (BarRef.current) {
          BarRef.current.resize()
        }
      }
    }))

    useEffect(() => {
      _initialOrSwitchAssociation('inital', selectedAssociationItem.key)
      return () => {
        clearCountUp()
      }
    }, [])

    const { data: carTypeData, run: run2 } = useRequest(
      async () => {
        const data = await getCrbtData({ entId: selectedAssociationItem.key })
        return data
      },
      {
        refreshDeps: [selectedAssociationItem.key, refreshFlag]
      }
    )
    // car龄分析数据
    type dataType = {
      xData: any[]
      yData: any[]
      yInfoData: any
    }
    const [echartData, setEchartData] = useState<dataType>({
      xData: [],
      yData: [],
      yInfoData: []
    })
    useRequest(
      async () => {
        const data = await getCarData({ entId: selectedAssociationItem.key })
        const x = [
          '1年内',
          '2年',
          '3年',
          '4年',
          '5年',
          '6-7年',
          '8-9年',
          '10年以上'
        ]
        const y: any = []
        const yInfoData = [
          '一年内',
          '2年',
          '3年',
          '4年',
          '5年',
          '6-7年',
          '8-9年',
          '10年以上'
        ]
        const xInfoData = [
          '0-1',
          '2-2',
          '3-3',
          '4-4',
          '5-5',
          '6-7',
          '8-9',
          '>10'
        ]
        xInfoData.map((v) => {
          let min: number | string
          let max: number | string
          if (v == '>10') {
            min = 10
            max = 99999
          } else {
            min = v.split('-')[0]
            max = v.split('-')[1]
          }
          let value = 0
          const ageData = data.filter(
            (v: any) =>
              Number(min) <= Number(v.name) && Number(v.name) <= Number(max)
          )
          const yz: any = []
          ageData.map((v: any) => {
            value += v.value
            if (v.value > 0) {
              yz.push({ age: String(v.name), value: v.value })
            }
          })
          y.push(value)
          yInfoData.push(yz)
        })
        function checkArrayForZeros(arr: any) {
          for (let i = 0; i < arr.length; i++) {
            if (arr[i] !== 0) {
              return true // 如果发现不为0的元素，返回true
            }
          }
          return false // 如果所有元素都为0，返回false
        }
        const a = checkArrayForZeros(y)

        function deepCompare(obj1: any, obj2: any) {
          if (obj1 === obj2) return true

          if (
            typeof obj1 !== 'object' ||
            typeof obj2 !== 'object' ||
            obj1 === null ||
            obj2 === null
          )
            return false

          const keys1 = Object.keys(obj1)
          const keys2 = Object.keys(obj2)

          if (keys1.length !== keys2.length) return false

          for (const key of keys1) {
            if (!keys2.includes(key)) return false
            if (!deepCompare(obj1[key], obj2[key])) return false
          }

          return true
        }

        const b = {
          xData: x,
          yData: a ? y : undefined,
          yInfoData: yInfoData
        }

        const result = deepCompare(echartData, b)
        if (result) {
          return
        } else {
          setEchartData(b)
        }
      },
      {
        refreshDeps: [selectedAssociationItem.key, refreshFlag]
      }
    )
    return (
      <div
        className="bigscreen-module ms-module"
        style={{ height: '564px', overflow: 'hidden' }}
      >
        <ModuleTitle
          title={'车辆数据分析'}
          // activeKey={0}
          // tab={[
          //   { name: "全部", value: 0 },
          //   { name: "属地", value: 1 },
          //   { name: "高频入境", value: 2 },
          //   { name: "过境", value: 3 }
          // ]}
          // tabChange={() => {}}
        ></ModuleTitle>
        <div
          className="bigscreen-content"
          style={{ paddingTop: 14, padding: 0 }}
        >
          <div style={{ padding: '14px 23px 0px 23px' }}>
            <div
              className="drvierCount flexr jub"
              style={{ minHeight: 53, maxHeight: 71, overflow: 'hidden' }}
            >
              <div style={{ width: '85px' }}>
                <div className="dr_count_num">
                  <CountUp
                    start={prevAllSum}
                    end={endAllSum}
                    duration={1}
                    onEnd={handleAllSumCountUpEnd}
                  />
                </div>
                <div className="dr_label">车辆入网总数</div>
              </div>
              <div style={{ width: '85px' }}>
                <div className="dr_count_num">
                  <CountUp
                    start={prevZySum}
                    end={endZySum}
                    duration={1}
                    onEnd={handleZySumCountUpEnd}
                  />
                </div>
                <div className="dr_label">今日作业车辆</div>
              </div>
              <div style={{ width: '85px' }}>
                <div className="dr_count_num">
                  <CountUp
                    start={prevZtSum}
                    end={endZtSum}
                    duration={1}
                    onEnd={handleZtSumCountUpEnd}
                  />
                </div>
                <div className="dr_label">当前在途车辆</div>
              </div>
            </div>
          </div>
          <div
            className="flexr alc  "
            style={{
              padding: '0px 23px',
              marginTop: 16,
              marginBottom: 25,
              height: 64,
              overflow: 'hidden'
            }}
          >
            <div style={{ width: '200px' }}>
              <MinPre
                data={optionData?.dlKvs || []}
                color={colorLinearData.slice(0, 3)}
                title="动力类型"
                ref={MinPreRef}
              ></MinPre>
            </div>
            <div style={{ width: '30px', height: '100px' }}></div>
            <div>
              <MinPre
                data={optionData?.gsKvs || []}
                color={colorLinearData.slice(3, 5)}
                title="车辆归属"
                ref={MinPreRef}
              ></MinPre>
            </div>
          </div>
          <div style={{ padding: '0 23px' }}>
            <LineP></LineP>
          </div>
          <div style={{ height: 180 }}>
            {/* <BigPre data={carTypeData || []} color={colorLinearData}></BigPre> */}
            <BigPre2
              data={carTypeData || []}
              color={colorLinearData}
              ref={BigPreRef}
            ></BigPre2>
          </div>
          <div style={{ padding: '0 23px' }}>
            <LineP></LineP>
          </div>
          <div
            style={{
              margin: '16px 0',
              height: 120,
              overflow: 'hidden',
              padding: '0 23px'
            }}
          >
            <BarModule
              title={'车龄分析'}
              data={echartData}
              ref={BarRef}
            ></BarModule>
          </div>
        </div>
      </div>
    )
  }
)

function LineP() {
  return (
    <div className="line-radius">
      <div className="line-pieicon"></div>
    </div>
  )
}

export default CarDataModule
